import * as crypto from 'crypto'
import { PassportStrategy } from '@nestjs/passport'
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { Strategy } from 'passport-local'
import { UserEntity } from 'src/user/user.entity'
import { AuthService } from './auth.service'

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      usernameField: 'mobile',
      passwordField: 'password'
    })
  }

  public async validate(mobile: string, password: string) {
    const hash = crypto.createHash('sha256')
    const hashPassword = hash.update(password).digest('hex')
    let user: UserEntity | null = null

    user = await this.authService.validateUserAccount(mobile)
    if (!user) {
      throw new UnauthorizedException()
    }

    user = await this.authService.validateUserAccountAndPasswd(
      mobile,
      hashPassword
    )
    if (!user) {
      throw new UnauthorizedException()
    }

    return user
  }
}
